﻿using System;
using SPCAF.Sdk;
using SPCAF.Sdk.Model;
using SPCAF.Sdk.Rules;
using SPCAFContrib.Entities.Consts;
using SPCAFContrib.Extensions;
using SPCAFContrib.Groups;

namespace SPCAFContrib.Rules.MasterPage
{
    [RuleMetadata(typeof(ContribCorrectnessGroup),
     CheckId = CheckIDs.Rules.ASPXMasterPage.SetAutoGenerateColumnsForSPGridViewInMasterPage,
     Help = CheckIDs.Rules.ASPXMasterPage.SetAutoGenerateColumnsForSPGridViewInMasterPage_HelpUrl,

     Message = "Set AutoGenerateColumns=false for SPGridView in the master page [{0}].",
     DisplayName = "Set AutoGenerateColumns=false for SPGridView in the master page.",
     Description = "The SPGridView control does not support the automatic generation of columns.",
     Resolution = "You always have to set the property AutoGenerateColumns to false and explicitly bind your columns using SPBoundField.",

     DefaultSeverity = Severity.Error,
     SharePointVersion = new[] { "12","14", "15" },
     Links = new[]
     {
         "SPGridView class",
         "http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spgridview.aspx"
     }
     )]
    public class SetAutoGenerateColumnsForSPGridViewInMasterPage : Rule<SolutionDefinition>
    {
        #region methods

        public override void Visit(SolutionDefinition target, NotificationCollection notifications)
        {
            foreach (InternalSourceFile internalSourceFile in target.AllFiles)
            {
                if (internalSourceFile.FileExtension.ToLower().Contains(".master"))
                {
                    internalSourceFile.FindControl("SPGridView", (controlDeclaration, lineNumber, linePosition) =>
                    {
                        if (controlDeclaration.IndexOf(" AutoGenerateColumns", StringComparison.InvariantCultureIgnoreCase) == -1 ||
                            controlDeclaration.IndexOf(" AutoGenerateColumns=\"true\"", StringComparison.InvariantCultureIgnoreCase) > 0)
                            Notify(target, String.Format(this.MessageTemplate(), target.ReadableElementName),
                                internalSourceFile.GetSummaryWithLineInfo(lineNumber, linePosition),
                                notifications);
                    });
                }
            }  
        }

        #endregion
    }
}
